package com.sunchangming.rpcgen;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

import freemarker.template.Template;
import freemarker.template.TemplateException;

@XStreamAlias("bean")
public class Bean extends UserType {
	ArrayList<Variable> vars = new ArrayList<Variable>();

	@XStreamAsAttribute
	public String sqltable;

	@XStreamAsAttribute
	public int code;

	@XStreamAsAttribute
	public String key;
	
	@XStreamAsAttribute
	public String baseclass;

	private Variable keyVar;

	public int getCode() {
		return code;
	}

	public Variable getKeyVar() {
		return keyVar;
	}

	public void generateCode(Path src, String language) throws IOException, TemplateException {
		final Path outputFile = parent.getDir(src).resolve(name + ".java");
		final freemarker.template.Configuration cfg = Main.getFreeMarkerConfig();
		final Template tmpl = cfg.getTemplate("beaninterface.tmpl");
		final Map<Object, Object> root = new HashMap<Object, Object>();
		root.put("packagename", parent.getFullName());
		root.put("classname", name);
		root.put("vars", vars);
		root.put("keyVar", keyVar);
		root.put("msgCode", code);
		root.put("sqltable", sqltable);
		root.put("baseclass", baseclass);
		tmpl.process(root, new OutputStreamWriter(Files.newOutputStream(outputFile), "utf-8"));
	}

	public String getBaseclass() {
		return baseclass;
	}

	void compile() {
		for (final Variable v : vars) {
			v.compile();
		}

		if (sqltable != null && !sqltable.isEmpty()) {
			if (key == null || key.isEmpty())
				key = "id";
			for (final Variable v : vars) {
				if (v.getName().equals(key)) {
					keyVar = v;
					break;
				}
			}
			if (keyVar == null)
				throw new RuntimeException(parent.getFullName() + "." + name + "需要一个名为" + key + "的字段");
		}
	}

}
